﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

public class Enemies : Characters
{
    //public enum EnemyState
    //{
    //    Walking,
    //    ChasingPlayer
    //}

    //Workaround to prevent all enemies having the same sequence of random numbers.
    private static Random randomGambi = new Random();
    private Random random = new Random(randomGambi.Next());
    private int walkingTime = 0;
    private float veloX, veloY;

    private Characters isChasing;
    public Characters IsChasing
    {
        get { return isChasing; }
        set { isChasing = value; }
    }

    public Enemies(float speed, float friction, Vector2 position)
        : base(speed, friction, position)
    {
    }

    /// <summary>
    /// Handles input, performs physics, and animates the player sprite.
    /// </summary>
    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);

        if (State != States.Dead)
        {
            ApplyPhysics(/*gameTime*/ false);
        }
    }

    public void RandomWalk(GameTime gameTime)
    {
        //Console.WriteLine("test = " + test + " GameTime = " + gameTime.ElapsedGameTime);
        walkingTime += gameTime.ElapsedGameTime.Milliseconds;
        if (walkingTime > 800)
        {
            veloX = (float)random.NextDouble() - 0.5f;
            veloY = (float)random.NextDouble() - 0.5f;
            walkingTime = 0;
        }
        Velocity.X += veloX;
        Velocity.Y += veloY;
    }

    public void ChasePlayer(Characters player)
    {
        Vector2 playerPosition = player.Position;

        isChasing = player;

        if (Position.X < playerPosition.X - 10)
        {
            Velocity.X += Speed;
        }
        else
        {
            if (Position.X > playerPosition.X + 10)
            {
                Velocity.X -= Speed;
            }
            else
            {
                Velocity.X = 0;
            }
        }
        if (Position.Y < playerPosition.Y - 10)
        {
            Velocity.Y += Speed;
        }
        else
        {
            if (Position.Y > playerPosition.Y + 10)
            {
                Velocity.Y -= Speed;
            }
            else
            {
                Velocity.Y = 0;
            }
        }
    }

    protected override void ApplyPhysics(/*GameTime gameTime*/ bool checkall)
    {
        Vector2 previousPosition = Position;

        Rectangle previuosBounding = BoundingRectangle;

        base.ApplyPhysics(/*gameTime*/ checkall);

        GameSession.HandleCollisions(Position, previousPosition, previuosBounding, BoundingRectangle, out position, false, null);

        if (Position.X == previousPosition.X)
            Velocity.X = 0;

        if (Position.Y == previousPosition.Y)
            Velocity.Y = 0;
    }
}